package com.ls.lserp.modules.setting.web;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import groovy.util.ResourceException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
	import javax.servlet.http.HttpServletResponse;
	import javax.servlet.http.HttpSession;
	import org.apache.shiro.authz.annotation.RequiresPermissions;
	import org.springframework.beans.factory.annotation.Autowired;
	import org.springframework.stereotype.Controller;
	import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.drew.lang.StringUtil;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.Material;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.setting.entity.CompanyList;
import com.ls.lserp.modules.setting.entity.CompanyUser;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.setting.entity.Personnel;
import com.ls.lserp.modules.setting.service.PersonnelService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.DictUtils;
import com.ls.lserp.modules.sys.utils.UserUtils;

	@Controller
	@RequestMapping(value = "${adminPath}/personnel/group")
	public class PersonnelController extends BaseController{
		@Autowired
	    private PersonnelService personnelService;

		/**
		 * 进入一览页面
		 * @param id
		 * @return
		 */
	    
		@ModelAttribute
		public Personnel get(@RequestParam(required=false) String id) {
			
			// 判断id是否为空
			if (StringUtils.isNotBlank(id)){
				
				// 执行查询语句 查询基本信息
				return personnelService.get(Long.parseLong(id));
			}else{
				
				// 若为空，实例化
				return new Personnel();
			}
			
		}
		
		/**
		 * 画面跳转用
		 * @param personnel
		 * @param model
		 * @return
		 */
		
		@RequiresPermissions("personnel:group:view")
		@RequestMapping(value = { "" })
		public String list(Personnel personnel, HttpServletRequest request, HttpServletResponse response, Model model) {

			// 返回页面地址
		    return "modules/setting/personnel";
		}

		/**
		 * @Title: 画面检索
		 * @Description: 查询页面 
		 * @param personnel
		 * @param request 
		 * @param response 
		 * @param model 
		 * @return searchList
		 * @throws ResourceException
		 */
		
		@RequiresPermissions("personnel:group:view")
		@RequestMapping(value = { "searchList" })
		@ResponseBody
		public String searchList(Personnel personnel, HttpServletRequest request, HttpServletResponse response, Model model)
				throws ResourceException {
			Map<Object, Object> listMap = new HashMap<Object, Object>();
			FileUtils filUtils = new FileUtils();
			DateFormat dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			
			// ajax回调时使用的一览list名
			request.setAttribute(Global.LIST_NAME, "personnel");
			
			// 画面取得的检索项目
			String groupName = personnel.getGroupName();
			String strUri = request.getContextPath() + Global.getAdminPath();
			// 拼接字符串供分页使用
			String searchParam = "&groupName=" + groupName;
			// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
			request.setAttribute(Global.SEARCH_PAEAM, searchParam);
			
			// 查询一览页面数据
			Page<Personnel> page = personnelService.findList(new Page<Personnel>(request, response), personnel);
			
			// 读取系统路径
			String basePath = SystemPath.getClassPath();
			String tempFilePath = "//"+basePath + "templates//demoHtml//personnel.txt";
			// 读取文件生成字符串
			String personnelHtml = readTxtFile(tempFilePath);
			String strHtml = "";
			String createUser = "";
			int pageNo = 0;
			if (!"".equals(personnelHtml)) {
				for (int i = 0; i < page.getList().size(); i++) {
					personnelHtml = filUtils.readFileToHtml(tempFilePath);
					// 画面No
					pageNo = (page.getPageNo() - 1) * page.getPageSize() + (i + 1);
					personnelHtml = personnelHtml.replace("pageNo", "" + pageNo);
					
					// 分组名称
					personnelHtml = personnelHtml.replace("groupName", StringUtils.checkStringNull(page.getList().get(i).getGroupName()));
					String groupNameline = "\"popup('900px','584px','" + strUri + "/personnel/group/show?id=" 
							+ page.getList().get(i).getId() + "')\"";
					// 分组名称popup
					personnelHtml = personnelHtml.replace("groupPopup", groupNameline);
					// 分组描述
					personnelHtml = personnelHtml.replace("groupDescription", StringUtils.checkStringNull(page.getList().get(i).getGroupDescription()));
					// 状态
					if ("1".equals(page.getList().get(i).getEnableFlag())) {
						personnelHtml = personnelHtml.replace("enableFlag", page.getTextMessage("personnel_open"));
					} else if ("0".equals(page.getList().get(i).getEnableFlag())) {
						personnelHtml = personnelHtml.replace("enableFlag", page.getTextMessage("personnel_close"));
					}
					// 创建人	
					createUser = page.getList().get(i).getCreateBy().getFirstName()
							+ page.getList().get(i).getCreateBy().getLastName();
					personnelHtml = personnelHtml.replace("createUser", createUser);
					
					// 创建日期
					dateForamat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
					Date createDate = page.getList().get(i).getCreateDate();
					if (createDate!=null) {
						personnelHtml = personnelHtml.replace("createDate", dateForamat.format(createDate));
					}else {
						personnelHtml = personnelHtml.replace("createDate", "");
					}
					strHtml += personnelHtml;
				}
			}
			listMap.put("personnel", strHtml);
			listMap.put("page", page.getHtml());
			// ajax返回结果
			return renderString(response, listMap);
		}
		
		/**
		 * 
		 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
		 * 3：读取到输入流后，需要读取生成字节流
		 * 
		 * @param filePath
		 * @return html
		 */
		public String readTxtFile(String filePath) {
			String strHtml = "";
			try {
				String encoding = "UTF-8";
				File file = new File(filePath);
				// 判断文件是否存在
				if (file.isFile()) {
					InputStreamReader read = new InputStreamReader(
							// 考虑到编码格式
							new FileInputStream(file), encoding);
					BufferedReader bufferedReader = new BufferedReader(read);
					String lingText = null;
					while ((lingText = bufferedReader.readLine()) != null) {
						strHtml += lingText;
					}
					read.close();
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return strHtml;
		}
		
		
		/**
	     * 进入查看页面
	     * @param personnel
	     * @param model
	     * @return
	     */
	    @RequiresPermissions("personnel:group:view")
	    @RequestMapping(value = "show")
	    public String show(Personnel personnel, Model model) {
	    	 
	    	
	    	personnel = personnelService.get(personnel);
	        // 将查询结果赋值mvc model层返回jsp页面
	        model.addAttribute("Personnel", personnel);
	        
	        // 返回页面地址
	        return "modules/setting/groupShow";
	    }
	    
		
		/**
		 * 新建
		 * @param personnel
		 * @param model
		 * @return
		 */
		@RequiresPermissions("personnel:group:edit")
		@RequestMapping(value = "form")
		public String form(Personnel personnel, RedirectAttributes redirectAttributes, Model model, HttpSession session) {

				// 将实体类值赋给mvc model层返回jsp页面
				model.addAttribute("personnel", personnel);
			
				// 返回页面地址
				return "modules/setting/groupCreate";
			}

		/**
		 * 保存
		 * @param personnel
		 * @param model
		 * @return
		 */
		@RequiresPermissions("personnel:group:edit")
		@RequestMapping(value = "save")
		@ResponseBody
		public String save(Personnel personnel, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {
			// 判断id是否为null （判断新建或修改）
						if(personnel.getId()!=null){
							
							// 判断数据是否删除
							Personnel personnelNew = get(personnel.getId().toString());
							// 判断数据是否删除
				            if(personnelNew==null || BaseEntity.DEL_FLAG_DELETE.equals(personnelNew.getDeleteFlag())){
				            	// 返回提示信息
				            	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
				            }
				       
						}
		        // 保存数据
			personnelService.saveUserGroup(personnel);
				
				// 保存成功返回提示信息
		        return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "customer_save_success")));
		}
		
		/**
		 * 删除信息
		 * @param personnel
		 * @param response
		 * @return
		 */
	    @RequiresPermissions("personnel:group:edit")
		@RequestMapping(value = "delete")
		public String delete(Personnel personnel, HttpServletResponse response) {
			
			    try {
			    	
			    	// 执行逻辑删除方法
			    	personnelService.deletePersonnel(personnel);
	            } catch (Exception e) {
	                // 记录日志
	                logger.error(e.getMessage(), e);
	            	// 提示错误信息
	                return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
	            }
			    
			    // 提示删除成功信息
				return renderString(response,AjaxDone.ok(getText("dict_delete_success")));
	    }
		
	}
